package com.xs.ahoi.hcxs.utils.tts;

import android.content.Context;
import com.xs.ahoi.hcxs.listener.AppTTSListener;
import com.xs.ahoi.hcxs.listener.TtsListener;
import com.xs.ahoi.hcxs.service.BookFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * author: cdfuhuichao
 * date: 2019/4/28 11:57
 * description:
 */
public abstract class AbstractTTS {

    public BookFactory bookFactory = BookFactory.getInstance();
    // TTS本页需要播放的文字行集合
    public List<String> pageLines = new ArrayList<>();
    // 本次播放的集合中的下标，上次播放时的下标，用于暂停后重新从上次位置开始播放
    public int lineIndexCurrent, lineIndexPrev;
    // 本次播放的文字行集合中的下标
    public List<Integer> lineIndexs = new ArrayList<>();

    public static TtsListener ttsListener;
    public static AppTTSListener appTTSListener;
    // 标记app页面是在正在播放
    public static boolean APP_PLAYING = false;

    // 获取本次播放的文字
    public String getSpeakText() {
        StringBuilder speakText = new StringBuilder();
        pageLines = bookFactory.getPagelines();
        lineIndexs.clear();

        lineIndexCurrent = lineIndexPrev;
        while (lineIndexCurrent < pageLines.size()) {
            // 获取本次播放的内容行下标，用于画文字时高亮显示播放的行
            lineIndexs.add(lineIndexCurrent);
            String lineText = pageLines.get(lineIndexCurrent);
            lineIndexCurrent++;
            speakText.append(lineText);
            if (lineText.endsWith("\n")) {
                break;
            }
        }

        bookFactory.setTtsPlayLineIndexs(lineIndexs);
        return speakText.toString();
    }

    public void next() {
        lineIndexPrev = lineIndexCurrent;
        if (lineIndexCurrent >= pageLines.size()) {
            try {
                // 读下一页的时候，延迟，避免最后几个字无法播放出来
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }
            ttsListener.nextPage();
        } else {
            start();
        }
    }

    public void appSpeakStart(String text, AppTTSListener appTTSListener) {
        AbstractTTS.appTTSListener = appTTSListener;
        APP_PLAYING = true;
        speakText(text);
    }

    public void appSpeakStop() {
        APP_PLAYING = false;
        onlyStop();
    }

    public abstract void init(Context context);

    public abstract boolean start();

    public abstract void onlyStop();

    public abstract boolean speakText(String text);

    public abstract void stop();

    public abstract void pause();

    public abstract void reset();

    public abstract void changeTtsParam();

    public void setTtsListener(TtsListener ttsListener) {
        this.ttsListener = ttsListener;
    }

}
